﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Transactions;
using NCS.IConnect;
using NCS.IConnect.ApplicationContexts;
using NCS.IConnect.AuditTrail;

namespace JM.JCY.Common
{
   public class OCPTransaction:IDisposable
    {
        
        public TransactionScope ts;
        public AuditLog al = null;
        public string transactionID;

        internal OCPTransaction()
        { }

        public OCPTransaction(string auditFunctionName, string userName)
        {
            transactionID = Guid.NewGuid().ToString();

            TransactionOptions to = new TransactionOptions();
            to.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;

            ts = new TransactionScope(TransactionScopeOption.Required, to);

            if (!string.IsNullOrEmpty(auditFunctionName))
            {
                al = new AuditLog(auditFunctionName, transactionID, userName);                
            }
        }

        public void Commit()
        {
            if (al != null) al.Flush();
            ts.Complete();
        }

        public void Dispose()
        {
            this.Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool isExplicit)
        {
            this.transactionID = string.Empty;
            try
            {
                if (ts != null) ts.Dispose();
            }
            catch
            { }
            try
            {
                if (al != null) al.Dispose();
            }
            catch
            {
            }
        }

        ~OCPTransaction()
        {
            Dispose(false);
        }
    }
}
